package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.utils.EmailUtils;
import com.qf.utils.MD5Utils;

public class UserServiceImpl implements UserService {
   private UserDao userDao = new UserDaoImpl();
    @Override
    public Boolean checkUserName(String username) {
        User user = userDao.selectByUsername(username);
        if (user != null) {
            return true;//用户已存在 "1" 不能注册
        }
        return false;//用户不存在 "0" 能注册
    }

    @Override
    public void register(User user) {
        //密码加密
        user.setPassword(MD5Utils.md5(user.getPassword()));
        userDao.insert(user);
        //发送邮件******(注册的时候发送邮件)
        EmailUtils.sendEmail(user);
    }

    @Override
    public void active(String email, String code) {
       int result =  userDao.updateFlag(email,code);//激活后改变flag:0变为1，所以相当于一个更新操作

    }

    @Override
    public User login(String username, String password) {
        //加密
        password = MD5Utils.md5(password);
        //查找用户
        User user = userDao.selectByUsername(username);
        //判断用户是否存在
        if (!user.getPassword().equalsIgnoreCase(password)){
            throw new RuntimeException("密码错误");
        }
        //是否激活
        if (user.getFlag()!=1){
            throw new RuntimeException("账户未激活");
        }
        return user;
    }

    @Override
    public User adminLogin(String username, String password) {
        //加密
        password = MD5Utils.md5(password);
        //查找用户
        User user = userDao.selectByUsername(username);
        //判断用户是否存在
        if (!user.getPassword().equalsIgnoreCase(password)){
            throw new RuntimeException("密码错误");
        }
        if (user.getRole()==0){
        return user;
        }
        throw new RuntimeException("账户不是管理员");
    }
}
